﻿using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Sfd.Entities;
using SfdClient.Messaging;

namespace SfdClient.ViewModel
{
    public class LogsViewModel : WorkingViewModelBase
    {
        public LogsViewModel()
        {
            var syncContext = SynchronizationContext.Current;
            LogEntries = new ObservableCollection<LogEntry>();


            Messenger.Default.Register<AddLogMessage>(
                this,
                message => syncContext.Send(
                    d =>
                        {
                            LogEntries.Add(new LogEntry
                                               {
                                                   Category = message.Category,
                                                   Message = message.LogMessage
                                               });
                            // on limite le nombre d'entrées à 100 lignes
                            if (LogEntries.Count>100)
                                LogEntries.RemoveAt(0);
                        },
                    message));

        }

        #region LogEntries Property

        /// <summary>
        /// The <see cref="LogEntries" /> property's name.
        /// </summary>
        public const string LogEntriesPropertyName = "LogEntries";

        private ObservableCollection<LogEntry> _logEntries;

        public ObservableCollection<LogEntry> LogEntries
        {
            get { return _logEntries; }

            private set
            {
                if (_logEntries == value) return;

                _logEntries = value;
                RaisePropertyChanged(LogEntriesPropertyName);
            }
        }

        #endregion

        #region ClearLogCommand

        private ICommand _clearLogCommand;

        public ICommand ClearLogCommand
        {
            get
            {
                if (_clearLogCommand == null)
                    _clearLogCommand = new RelayCommand(ExecuteClearLogCommand, CanExecuteClearLogCommand);
                return _clearLogCommand;
            }
        }

        public void ExecuteClearLogCommand()
        {
            if (!CanExecuteClearLogCommand())
                return;
            
            LogEntries.Clear();
        }

        public bool CanExecuteClearLogCommand()
        {
            return true;
        }

        #endregion


    }
}
